import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:http/http.dart' as http;

/// 图片预览组件
/// 用于显示图片类型文件的预览
class ImagePreview extends StatelessWidget {
  final String? previewUrl;
  final String? fileName;
  final VoidCallback? onRetry;

  const ImagePreview({
    Key? key,
    required this.previewUrl,
    this.fileName,
    this.onRetry,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    if (previewUrl == null) {
      return const Center(child: Text('无法加载图片预览'));
    }

    return FutureBuilder<http.Response>(
      future: http.get(
        Uri.parse(previewUrl!),
        headers: {
          'User-Agent':
              'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
          'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8',
          'Cache-Control': 'no-cache',
        },
      ),
      builder: (context, snapshot) {
        // 加载中
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                CircularProgressIndicator(),
                SizedBox(height: 16),
                Text('图片加载中...'),
              ],
            ),
          );
        }

        // 加载成功
        if (snapshot.connectionState == ConnectionState.done &&
            snapshot.hasData &&
            snapshot.data!.statusCode == 200) {
          return Center(
            child: Column(
              children: [
                Expanded(
                  child: InteractiveViewer(
                    minScale: 0.5,
                    maxScale: 3.0,
                    child: Image.memory(
                      snapshot.data!.bodyBytes,
                      fit: BoxFit.contain,
                    ),
                  ),
                ),
                // 下载按钮
                Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: ElevatedButton.icon(
                    onPressed: () async {
                      final url = Uri.parse(previewUrl!);
                      if (await canLaunchUrl(url)) {
                        await launchUrl(
                          url,
                          mode: LaunchMode.externalApplication,
                        );
                      }
                    },
                    icon: const Icon(Icons.download),
                    label: const Text('下载图片'),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Theme.of(context).primaryColor,
                      foregroundColor: Colors.white,
                    ),
                  ),
                ),
              ],
            ),
          );
        }

        // 加载失败
        String errorMessage = '无法加载图片';
        if (snapshot.hasError) {
          errorMessage = snapshot.error.toString();
          return _buildImageErrorWidget(context, snapshot.error!);
        } else if (snapshot.hasData && snapshot.data!.statusCode != 200) {
          errorMessage = '状态码: ${snapshot.data!.statusCode}\n';
          if (snapshot.data!.body.contains('SignatureDoesNotMatch')) {
            errorMessage += '签名验证失败，URL可能已过期';
          } else {
            errorMessage +=
                snapshot.data!.body.length > 300
                    ? snapshot.data!.body.substring(0, 300) + '...'
                    : snapshot.data!.body;
          }
          return _buildImageErrorWidget(context, errorMessage);
        } else {
          return _buildImageErrorWidget(context, '未知错误');
        }
      },
    );
  }

  /// 构建图片错误显示组件
  Widget _buildImageErrorWidget(BuildContext context, Object error) {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(Icons.broken_image, size: 64, color: Colors.grey[400]),
          const SizedBox(height: 16),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 32.0),
            child: Text(
              '图片加载失败',
              style: TextStyle(
                color: Colors.red[300],
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
              textAlign: TextAlign.center,
            ),
          ),
          const SizedBox(height: 8),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 32.0),
            child: Text(
              error.toString().length > 100
                  ? '${error.toString().substring(0, 100)}...'
                  : error.toString(),
              style: TextStyle(color: Colors.grey[600]),
              textAlign: TextAlign.center,
            ),
          ),
          const SizedBox(height: 16),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(onPressed: onRetry, child: const Text('重试')),
              const SizedBox(width: 16),
              ElevatedButton.icon(
                onPressed: () async {
                  final url = Uri.parse(previewUrl!);
                  if (await canLaunchUrl(url)) {
                    await launchUrl(url, mode: LaunchMode.externalApplication);
                  }
                },
                icon: const Icon(Icons.download),
                label: const Text('下载图片'),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
